package com.gientecher.redisdemo.controller;

import com.gientecher.redisdemo.entity.RedisLockEntity;
import com.gientecher.redisdemo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisLockController {

    @Autowired
    private RedisService redisService;

    /**
     * 测试分布式锁
     * @return
     */
    @GetMapping(value = "/testRedisLock")
    public String testRedislock1() {
        System.out.println("start....lock");
        RedisLockEntity redisLockEntity = new RedisLockEntity();
        redisLockEntity.setLockKey("lockkey");
        redisLockEntity.setRequestId("1");
        boolean lock = redisService.lock(redisLockEntity);
        if (lock){//如果上锁成功
            System.out.println("lock success!");

            // 业务代码

            this.testRedisUnlock2();// 更新订单完成后，释放锁。
        } else { // 如果上锁不成功
            System.out.println("lock fail!");

            //此时没拿到锁，则不能更新订单数量。可以采取自旋直到抢到锁为止再去更新订单数量；或者是执行其它业务。
            // 业务代码
        }
        System.out.println("end.....lock");
        return "success";
    }

    /**
     * 释放锁业务
     * @return
     */
    public String testRedisUnlock2() {
        System.out.println("start....unlock");
        RedisLockEntity redisLockEntity = new RedisLockEntity();
        redisLockEntity.setLockKey("lockkey");
        redisLockEntity.setRequestId("1");
        boolean unlock = redisService.unlockLua(redisLockEntity);
        if (unlock){
            System.out.println("unlock success!");
        } else {
            System.out.println("unlock fail!");
        }

        System.out.println("end....unlock");
        return "success";
    }
}
